package me.zhengjie.modules.lock.util;

import com.zelk.smartlock.common.response.Response;
import com.zelk.smartlock.common.response.ResponsePage;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.utils.JsonUtil;

import java.util.List;
import java.util.Optional;
import java.util.function.Function;


@Slf4j
public class RequestCall {

    /**
     * 执行方法
     *
     * @param <T>
     * @param <R>
     * @param cmdExecuteFunction
     * @param t
     * @return
     */
    public static <T, R> R execute(Function<T, Response<R>> cmdExecuteFunction, T t, String errorDesc) {
        Response<R> response = cmdExecuteFunction.apply(t);
        log.info("response:{}", JsonUtil.toJson(response));
        if (response.getErrorCode() == 0) {
            return response.getData();
        }

        log.error("接口调用失败，t:{}", t);

        //如果没有传描述，则默认用这个错误提示
        errorDesc = Optional.ofNullable(errorDesc).orElse("");
        errorDesc += response.getMessage();

        log.info("调用openApi异常信息:{}", errorDesc);
        throw new BadRequestException(errorDesc);
    }

    /**
     * 执行方法
     *
     * @param <T>
     * @param <R>
     * @param cmdExecuteFunction
     * @param t
     * @return
     */
    public static <T, R> ResponsePage<List<R>> executePage(Function<T, ResponsePage<List<R>>> cmdExecuteFunction, T t, String errorDesc) {
        ResponsePage<List<R>> response = cmdExecuteFunction.apply(t);
        log.info("response:{}", JsonUtil.toJson(response));
        if (response.getErrorCode() == 0) {
            return response;
        }

        log.error("接口调用失败，t:{}", t);

        //如果没有传描述，则默认用这个错误提示
        errorDesc = Optional.ofNullable(errorDesc).orElse("");
        errorDesc += response.getMessage();

        log.info("调用openApi异常信息:{}", errorDesc);
        throw new BadRequestException(errorDesc);
    }

}
